package main

import (
	"context"
	"fmt"
	"io"
	"mime"
	"net/http"
	"os/exec"
	"runtime"
	"strings"

	"go.bug.st/serial/enumerator"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called at application startup
func (a *App) startup(ctx context.Context) {
	// Perform your setup here
	a.ctx = ctx
}

// domReady is called after front-end resources have been loaded
func (a App) domReady(ctx context.Context) {
	// Add your action here
}

// beforeClose is called when the application is about to quit,
// either by clicking the window close button or calling runtime.Quit.
// Returning true will cause the application to continue, false will continue shutdown as normal.
func (a *App) beforeClose(ctx context.Context) (prevent bool) {
	return false
}

// shutdown is called at application termination
func (a *App) shutdown(ctx context.Context) {
	// Perform your teardown here
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}

func (a *App) GetSerialPortList() []*enumerator.PortDetails {
	s, _ := enumerator.GetDetailedPortsList()
	return s
}

func (a *App) OpenInBrowser(url string, arguments []string) error {
	var cmd string
    var args []string

    switch runtime.GOOS {
    case "windows":
        cmd = "cmd"
        args = []string{"/c", "start"}
    case "darwin":
        cmd = "open"
    default: // "linux", "freebsd", "openbsd", "netbsd"
        cmd = "xdg-open"
    }

    args = append(args, url)
	args = append(args, arguments...)
    return exec.Command(cmd, args...).Start()
}
// PostJson sends a JSON payload to the specified server URL using the http package and returns the response as a string.
func (a *App) PostJson(url string, jsonStr string) (string, error) {
    req, err := http.NewRequest("POST", url, strings.NewReader(jsonStr))
    if err != nil {
        return "", err
    }
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Accept", "application/json")
    req.Header.Set("User-Agent", "ProtocolTester/1.0.0")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
         return "", fmt.Errorf("HTTP error: status code %d", resp.StatusCode)
    }
    ct := resp.Header.Get("Content-Type")
    mediaType, _, _ := mime.ParseMediaType(ct)
    if mediaType != "application/json" {
        return "",  fmt.Errorf("unexpected content type: %s", ct)
    }
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }
    return string(body), nil
}

